package com.hand.wfive.activity

import androidx.core.splashscreen.SplashScreen
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.splashscreen.SplashScreenViewProvider
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.view.PrivacyDialog
import com.umeng.commonsdk.UMConfigure
import kotlinx.coroutines.*
import org.jetbrains.anko.startActivity
import java.util.concurrent.atomic.AtomicBoolean

class StartActivity : BaseActivity() {

    private var mOver = false
    private lateinit var mSplashScreen: SplashScreen
    private lateinit var mCoroutineScope: CoroutineScope
    private val mKeepOnAtomicBool = AtomicBoolean(true)

    override fun setContentViewBefore() {
        super.setContentViewBefore()
        mSplashScreen = installSplashScreen()
    }

    override fun getContentViewId() = R.layout.activity_start

    override fun init() {
        // 每次UI绘制前，会判断 Splash 是否有必要继续展示在屏幕上；直到不再满足条件时，隐藏Splash。
        mSplashScreen.setKeepVisibleCondition { mKeepOnAtomicBool.get() }
        // Splash展示完毕的监听方法
//        mSplashScreen.setOnExitAnimationListener { checkFirst(it) }
        // 创建 CoroutineScope （用于管理CoroutineScope中的所有协程）
        mCoroutineScope = CoroutineScope(Job() + Dispatchers.Main)
        mCoroutineScope.launch(Dispatchers.IO) {
            // Splash 展示完毕
            mOver = true
            mKeepOnAtomicBool.compareAndSet(true, false)
        }
    }

    private fun checkFirst(splashScreenViewProvider: SplashScreenViewProvider? = null) {
        val isFirst = PrivacyDialog.showPrivacy(this, object : PrivacyDialog.OnClickBottomListener {
            override fun onPositiveClick(dialog:PrivacyDialog ) {
                dialog.dismiss()
                splashScreenViewProvider?.remove()
                turnLauncher()
            }

            override fun onNegtiveClick() {
                splashScreenViewProvider?.remove()
                finish()
            }
        })
        if (!isFirst) {
            splashScreenViewProvider?.remove()
            turnLauncher()
        }
    }

    private fun turnLauncher() {
        UMConfigure.submitPolicyGrantResult(App.getContext(), true)

        startActivity<LauncherActivity>()
        finish()

        overridePendingTransition(0, 0)
    }

    override fun onResume() {
        super.onResume()
        if (mOver) checkFirst()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 当 Activity 销毁的时候取消该 Scope 管理的所有协程。
        mCoroutineScope.cancel()
    }
}